const app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [{
      img: "../../images/product.png"
    },
    {
      img: "../../images/product.png"
    }
    ],
    is_like: false,
    tab_key: "pro_des", // 详情：pro_des，属性：pro_nature
    num: 1,
    // 使用data数据对象设置样式名  
    minusStatus: 'disabled',
    is_show_modal: false,
    price: '',
    pro_price: '', //原价
    pro_name: '',
    sold: '', //已卖出
    surplus: '', //剩余
    pro_detail: '', //详情 富文本
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log("上个页面id",options)
    let id = options.id
    let pro_id = options.pro_id

    wx.getStorage({
      key: 'openid',
      success: function(res) {
        let openid = res.data
        wx.showLoading({
          title: '加载中',
        })
        wx.request({
          url: app.globalData.URL + '/app/seckill/index?id=' + id + '&proId=' + pro_id + '&openid='+openid,
          success: function (res) {
            wx.hideLoading()
            console.log(res)
            var img1 = res.data.qhcPro.productPicture
            var img2 = res.data.qhcPro.productPicTwo
            var img3 = res.data.qhcPro.productPicPhree;
            //轮播图(返回数据竟然用的是富文本！！)
            WxParse.wxParse('rich_img1', 'html', img1, that, 0);
            WxParse.wxParse('rich_img2', 'html', img2, that, 0);
            WxParse.wxParse('rich_img3', 'html', img3, that, 0);

            //商品详情图
            var img_detail = res.data.qhcPro.productDetailsPic
            WxParse.wxParse('img_detail', 'html', img_detail, that, 0);

            //商品图
            var pro_img = res.data.qhcPro.productClassPic
            WxParse.wxParse('pro_img', 'html', pro_img, that, 0);
            that.setData({
              pro_name: res.data.qhcPro.productName,
              price: res.data.seckill.price,
              pro_price: res.data.qhcPro.productPrice,
              surplus: res.data.seckill.inventory,
              sold: res.data.seckill.number - res.data.seckill.inventory,
              pro_detail: img_detail,
              pro_id: res.data.seckill.product,
              seckillId: res.data.seckill.id,
              startTime: res.data.seckill.startTime,
              reservation: res.data.seckill.reservation
            })

            let time = new Date(that.data.startTime) - new Date();
            console.log("time:",time)
            that.setData({
              time:time
            })
            if(time > 0){
              that.ms_countdown(that)
            }
            
          }
        })
      },
    })
    
  },
  // 倒计时
  ms_countdown: function (that) {
    var EndTime = new Date(that.data.startTime).getTime() || [];
    // console.log(EndTime);
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];  //单位毫秒
    if (total_micro_second < 0) {
      // console.log('时间初始化小于0，活动已结束状态');
      total_micro_second = 1;   //单位毫秒 ------ WHY？
      return
    }
    // 渲染倒计时时钟
    that.setData({
      clock: '距秒杀开始' + that.dateformat(total_micro_second)  //若已结束，此处输出'0天0小时0分钟0秒'
    });
    setTimeout(function () {
      total_micro_second -= 1000;
      that.ms_countdown(that);
    }, 1000)
  },

  // 时间格式化输出，如11天03小时25分钟19秒 每1s都会调用一次
  dateformat: function (micro_second) {
    // 总秒数
    var second = Math.floor(micro_second / 1000);
    // 天数
    var day = Math.floor(second / 3600 / 24);
    // 小时
    var hr = Math.floor(second / 3600 % 24);
    // 分钟
    var min = Math.floor(second / 60 % 60);
    // 秒
    var sec = Math.floor(second % 60);
    return day + "天" + hr + "时" + min + "分" + sec + "秒";
  },
  skipShoppingCart: function () {
    wx.navigateTo({
      url: '../shoppingCart/shoppingCart'
    })
  },
  skipMy: function () {
    wx.switchTab({
      url: '/my/my'
    })
  },
  showModal: function () {
    this.setData({
      is_show_modal: true
    })
  },
  closeModal: function () {
    this.setData({
      is_show_modal: false
    })
  },
  changeDes: function () {
    this.setData({
      tab_key: "pro_des"
    })
  },
  changeNature: function () {
    this.setData({
      tab_key: "pro_nature"
    })
  },

  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减  
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var num = this.data.num;
    // 不作过多考虑自增1  
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    // 将数值与状态写回  
    this.setData({
      num: num
    });
  },
 
  addShopping: function () {
    var that = this

    wx.getStorage({
      key: 'openid',
      success: function(res) {
        let openid = res.data

        wx.request({
          url: app.globalData.URL + '/app/product/addShopping?proId=' + that.data.pro_id + '&num=' + that.data.num + '&openid=' + openid,
          success: function (res) {
            console.log(res)
            if (res.data.msg == true) {
              wx.showToast({
                title: '加入成功',
                icon: 'success',
                duration: 5000
              })
            } else {
              wx.showToast({
                title: '加入购物车失败',
                image: '../../images/error.png',
                duration: 5000
              })
            }
          }
        })
      },
    })
    
  },

  toPay:function(){
    wx.navigateTo({
      url: '../tg_ms_shoppingList/tg_ms_shoppingList?ids=' + this.data.pro_id + '&number=' + this.data.num + '&money=' + this.data.price * this.data.num + '&isPro=3' + '&seckillId=' + this.data.seckillId,
    })
  },

  yuyue:function(){
    var that = this
    var openid = wx.getStorageSync('openid')
    wx.request({
      url: app.globalData.URL + '/app/seckill/yuyue?productId=' + that.data.pro_id + '&seckillId=' + that.data.seckillId + '&openid=' + openid,
      success:function(res){
        console.log(res)
        if(res.data.flag == true){
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
        }
      }
    })
  }
})